package com.haoxi.gateway.cmpp30msg;

/**
 * Title:CMPP3.0,200409
 **/

import java.io.IOException;
import java.io.OutputStream;


/**
 * ʵ��CMPP3.0 CMPP_Connect
 */
public class CMPPConnect {
    private byte[] outbytes;

    /**
     * ����һ��CMPP_Connect
     *
     * @param SequenceID
     * @param ICP_ID     �ƶ���ط������ҵ����
     * @param Password   �ƶ���ط��������
     */
    public CMPPConnect ( int SequenceID, String ICP_ID, String Password ) {
        this ( SequenceID, ICP_ID, Password, 30 );
    }

    /**
     * ����һ��CMPP_Connect
     *
     * @param version �汾��
     * @see CMPPConnect#CMPPConnect()
     */
    public CMPPConnect ( int SequenceID, String ICP_ID, String Password, int version ) {
        byte[] bodybytes = new byte[CMPPCommon.MSG_CONNECT_BODY_LENGTH];
        int ilength = ICP_ID.length () + Password.length () + 9 + 10;
        byte md5inputbytes[] = new byte[ilength];
        byte md5resultbytes[] = new byte[16];
        String timeStamp = CMPPCommon.getTimeStamp ();
        timeStamp.getBytes ( 0, timeStamp.length (), md5inputbytes, ilength - 10 );
        Password.getBytes ( 0, Password.length (), md5inputbytes, ilength - 10 - Password.length () );
        ICP_ID.getBytes ( 0, ICP_ID.length (), md5inputbytes, 0 );
        MD5 md5 = new MD5 ();
        md5.Init ();
        md5.Update ( md5inputbytes, 0, ilength );
        md5resultbytes = md5.Final ();
        ICP_ID.getBytes ( 0, ICP_ID.length (), bodybytes, 0 );
        CMPPCommon.BytesCopy ( md5resultbytes, bodybytes, 0, 15, 6 );
        bodybytes[ 22 ] = ( byte ) version;
        CMPPCommon.BytesCopy ( CMPPCommon.IntToBytes4 ( Integer.parseInt ( timeStamp ) ), bodybytes, 0, 3, 23 );
        CMPPMsgHead head = new CMPPMsgHead ( CMPPCommon.MSG_HEAD_LENGTH + CMPPCommon.MSG_CONNECT_BODY_LENGTH, CMPPCommon.CMPP_CONNECT, SequenceID );
        byte[] msgHead = head.getMsgHead ();
        outbytes = new byte[CMPPCommon.MSG_HEAD_LENGTH + bodybytes.length];
        CMPPCommon.BytesCopy ( msgHead, outbytes, 0, msgHead.length - 1, 0 );
        CMPPCommon.BytesCopy ( bodybytes, outbytes, 0, bodybytes.length - 1, msgHead.length );
    }

    /**
     * ���CMPP_Connect��
     *
     * @param out �����
     * @throws IOException ������IOΥ��
     */
    public void write ( OutputStream out ) throws IOException {
        if ( outbytes == null ) {
            throw new IOException ( "CMPPConnect outbytes is NULL" );
        }
        out.write ( outbytes );
        out.flush ();
    }

    /**
     * ȡ��CMPP_CONNECT��
     *
     * @return
     */
    public byte[] getbytes () {
        return outbytes;
    }
}